package com.weixin.util;

import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.util.StringUtils;

/**
 * @author lc
 * @email 389125111@qq.com
 * @create 2018-04-19 14:11
 */
public class PasswordHelper {
    private static RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
    private static final String algorithmName = "md5";
    private static final int hashIterations = 2;

    /**
     * 验证密码是否正确
     *
     * @param salt     盐
     * @param password 需要用来对比的密码串
     * @param md5Pwd   通过盐生成的密码串
     * @return 正确返回true，否则false
     */
    public static boolean validatePwd(String salt, String password, String md5Pwd) {
        if (StringUtils.isEmpty(salt) || StringUtils.isEmpty(password) || StringUtils.isEmpty(md5Pwd)) {
            return false;
        }
        return md5Pwd.equals(encryptPwd(password, salt));
    }

    /**
     * 根据盐获取新的密码
     *
     * @param password 原密码
     * @param salt     盐
     * @return 新密码
     */
    public static String encryptPwd(String password, String salt) {
        return new SimpleHash(algorithmName, password, ByteSource.Util.bytes(salt), hashIterations).toHex();
    }

    /**
     * 获取长度为32位的随机盐
     *
     * @return 盐
     */
    public static String getSalt() {
        return randomNumberGenerator.nextBytes().toHex();
    }


    public static void main(String[] args) {
        String psw = "e10adc3949ba59abbe56e057f20f883e";
        String salt = PasswordHelper.getSalt();
        String encryptPwd = PasswordHelper.encryptPwd(psw, salt);

        System.out.println("salt:    " + salt);
        System.out.println("encryptPwd:    " + encryptPwd);
        System.out.println("encryptPwd:    " + encryptPwd.length());
        System.out.println(PasswordHelper.validatePwd(salt, psw, encryptPwd));
    }

}
